package com.songlanyun.modules.pointtobalace.controller;

import java.net.URLEncoder;
import java.text.ParseException;
import java.util.*;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.poi.excel.ExcelUtil;
import com.songlanyun.common.annotation.AuthIgnore;
import com.songlanyun.common.utils.DateUtils;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.R;
import com.songlanyun.modules.chain.model.dto.UserWithdrawalDTO;
import com.songlanyun.modules.keywordsearch.entity.SystemKeyWordSearch;
import com.songlanyun.modules.order.model.vo.OrderVO;
import com.songlanyun.modules.pointtobalace.entity.BalanceToPointRecordCNHD;
import com.songlanyun.modules.pointtobalace.model.vo.BalanceToPointRecordCNHDVO;
import com.songlanyun.modules.pointtobalace.model.vo.BalanceToPointRecordCNHDVO2;
import com.songlanyun.modules.pointtobalace.vo.BalanceToPointRecordCNHDRequest;
import com.songlanyun.modules.user.controller.AbstractController;
import com.songlanyun.modules.userbank.dao.UserBankDao;
import com.songlanyun.modules.userbank.entity.UserBank;
import com.songlanyun.modules.userbank.service.UserBankService;
import lombok.extern.java.Log;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.songlanyun.modules.pointtobalace.service.IBalanceToPointRecordCNHDService;


/**
 * 积分兑换成余额(消费额余额)Controller
 *
 * @author SH
 * @date 2024-03-05
 */
@RestController
@RequestMapping("api/pointtobalace/pointtobalacecnhd")
public class BalanceToPointRecordCNHDController extends AbstractController
{
    @Autowired
    private IBalanceToPointRecordCNHDService balanceToPointRecordCNHDService;

    @Autowired
    private UserBankDao userBankDao;

//    /**
//     * 查询积分兑换成余额(消费额余额)列表
//     */
////    @PreAuthorize("@ss.hasPermi('pointtobalace:pointtobalacecnhd:list')")
//    @GetMapping("/list")
//    public R list(BalanceToPointRecordCNHD balanceToPointRecordCNHD)
//    {
//        List<BalanceToPointRecordCNHD> list = balanceToPointRecordCNHDService.selectBalanceToPointRecordCNHDList(balanceToPointRecordCNHD);
//        return R.ok().put("list", list);
//    }

    /**
     * 查询积分兑换成余额(消费额余额)列表
     */
//    @PreAuthorize("@ss.hasPermi('pointtobalace:pointtobalacecnhd:list')")
    @GetMapping("/list")
    public R list(@RequestParam Map<String, String> params) throws ParseException {
        PageUtils page = balanceToPointRecordCNHDService.allExaminePage(params);
        return R.ok().put("list", page);
    }

    /**
     * 导出积分兑换成余额(消费额余额)列表
     *
     * @param params 列表的查询参数
     * @param response 能输出Excel数据给客户端的Response实例
     * @throws Exception 导出过程中可能发生的例外
     *
     * @since 2024-04-11
     * @author 王熙伟
     */
    @GetMapping("/export")
    @AuthIgnore
    //@RequiresPermissions("usergains:distributionuserordergains:list")
    public void export(@RequestParam Map<String, String> params, HttpServletResponse response) throws Exception {
        String sortType = params.get("sort_type");
        if(sortType != null){
            params.put("sort_type", sortType.toUpperCase());
        }

        Long adminId = this.getAdminByToken(response);//校验token
        List<BalanceToPointRecordCNHDVO> balanceToPointRecordCNHDList = balanceToPointRecordCNHDService.exportList(params);

        String fileName = "积分兑换成余额(消费额余额)列表" + DateUtils.format(new Date(), "yyyy-MM-dd-HHmmss") + "_" + adminId + "." + "xls";
        ExportParams exportParams = new ExportParams("商品订单列表导出(" + balanceToPointRecordCNHDList.size() + ")", "积分兑换成余额(消费额余额)列表");

        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, BalanceToPointRecordCNHDVO.class, balanceToPointRecordCNHDList);
        response.setContentType(new MimetypesFileTypeMap().getContentType("application/octet-stream"));// 设置response内容的类型
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));// 设置头部信息
        sheets.write(response.getOutputStream());
        sheets.close();
    }

    /**
     * 导出积分兑换成余额(消费额余额)列表
     *
     * @param params 列表的查询参数
     * @param response 能输出Excel数据给客户端的Response实例
     * @throws Exception 导出过程中可能发生的例外
     *
     * @since 2024-04-11
     * @author 王熙伟
     */
    @GetMapping("/export2")
    @AuthIgnore
    //@RequiresPermissions("usergains:distributionuserordergains:list")
    public void export2(@RequestParam Map<String, String> params, HttpServletResponse response) throws Exception {
        String sortType = params.get("sort_type");
        if(sortType != null){
            params.put("sort_type", sortType.toUpperCase());
        }

        Long adminId = this.getAdminByToken(response);//校验token
        List<BalanceToPointRecordCNHDVO2> balanceToPointRecordCNHDList = balanceToPointRecordCNHDService.exportList2(params);

        String fileName = "积分兑换成余额(消费额余额)列表" + DateUtils.format(new Date(), "yyyy-MM-dd-HHmmss") + "_" + adminId + "." + "xls";
        ExportParams exportParams = new ExportParams("商品订单列表导出(" + balanceToPointRecordCNHDList.size() + ")", "积分兑换成余额(消费额余额)列表");

        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, BalanceToPointRecordCNHDVO2.class, balanceToPointRecordCNHDList);
        response.setContentType(new MimetypesFileTypeMap().getContentType("application/octet-stream"));// 设置response内容的类型
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));// 设置头部信息
        sheets.write(response.getOutputStream());
        sheets.close();
    }

//    /**
//     * 导出积分兑换成余额(消费额余额)列表
//     */
//    @PreAuthorize("@ss.hasPermi('pointtobalace:pointtobalacecnhd:export')")
//    @Log(title = "积分兑换成余额(消费额余额)", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, BalanceToPointRecordCNHD balanceToPointRecordCNHD)
//    {
//        List<BalanceToPointRecordCNHD> list = balanceToPointRecordCNHDService.selectBalanceToPointRecordCNHDList(balanceToPointRecordCNHD);
//        ExcelUtil<BalanceToPointRecordCNHD> util = new ExcelUtil<BalanceToPointRecordCNHD>(BalanceToPointRecordCNHD.class);
//        util.exportExcel(response, list, "积分兑换成余额(消费额余额)数据");
//    }

    /**
     * 获取积分兑换成余额(消费额余额)详细信息
     */
//    @PreAuthorize("@ss.hasPermi('pointtobalace:pointtobalacecnhd:query')")
    @GetMapping(value = "/{id}")
    public R getInfo(@PathVariable("id") Long id)
    {
        BalanceToPointRecordCNHD balanceToPointRecordCNHD = balanceToPointRecordCNHDService.selectBalanceToPointRecordCNHDById(id);
        return R.ok().put("data",balanceToPointRecordCNHD);
    }

    /**
     * 新增积分兑换成余额(消费额余额)
     */
//    @PreAuthorize("@ss.hasPermi('pointtobalace:pointtobalacecnhd:add')")
//    @Log(title = "积分兑换成余额(消费额余额)", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody BalanceToPointRecordCNHD balanceToPointRecordCNHD)
    {
        int i = balanceToPointRecordCNHDService.insertBalanceToPointRecordCNHD(balanceToPointRecordCNHD);
        if (i>0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改积分兑换成余额(消费额余额)
     */
//    @PreAuthorize("@ss.hasPermi('pointtobalace:pointtobalacecnhd:edit')")
//    @Log(title = "积分兑换成余额(消费额余额)", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public R edit(@RequestBody BalanceToPointRecordCNHD balanceToPointRecordCNHD)
    {
        int i = balanceToPointRecordCNHDService.updateBalanceToPointRecordCNHD(balanceToPointRecordCNHD);
        if (i>0){
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改积分兑换成余额(消费额余额)
     */
//    @PreAuthorize("@ss.hasPermi('pointtobalace:pointtobalacecnhd:edit')")
//    @Log(title = "积分兑换成余额(消费额余额)", businessType = BusinessType.UPDATE)
    @PostMapping("/batch-to-edit")
    public R batchToEdit(@RequestBody BalanceToPointRecordCNHDRequest balanceToPointRecordCNHDRequest)
    {
        List<Integer> result = new ArrayList<>();
        if(balanceToPointRecordCNHDRequest != null
        && balanceToPointRecordCNHDRequest.getBalanceToPointRecordCNHDs() != null
        && balanceToPointRecordCNHDRequest.getBalanceToPointRecordCNHDs().length > 0
        && balanceToPointRecordCNHDRequest.getExamine() != null
        && balanceToPointRecordCNHDRequest.getExamine() >= 0
        && balanceToPointRecordCNHDRequest.getExamine() <= 2){
            BalanceToPointRecordCNHD[] balanceToPointRecordCNHDS = balanceToPointRecordCNHDRequest.getBalanceToPointRecordCNHDs();
            for(int i = 0; i < balanceToPointRecordCNHDS.length; i++){
                BalanceToPointRecordCNHD balanceToPointRecordCNHD = balanceToPointRecordCNHDS[i];
                balanceToPointRecordCNHD.setExamine(balanceToPointRecordCNHDRequest.getExamine());
                int eachResult = balanceToPointRecordCNHDService.updateBalanceToPointRecordCNHD(balanceToPointRecordCNHD);
                if(eachResult == 0){
                    result.add(eachResult);
                }
            }
        } else {
            return R.error("未提交任何有效数据，操作取消");
        }

        if(!result.isEmpty()){
            return R.error("以下记录已设定为“未审核”的状态：" + Arrays.toString(result.toArray()));
        } else {
            return R.ok();
        }
    }

//    /**
//     * 删除积分兑换成余额(消费额余额)
//     */
////    @PreAuthorize("@ss.hasPermi('pointtobalace:pointtobalacecnhd:remove')")
////    @Log(title = "积分兑换成余额(消费额余额)", businessType = BusinessType.DELETE)
//	@DeleteMapping("/{ids}")
//    public R remove(@PathVariable Long[] ids)
//    {
//        return toAjax(balanceToPointRecordCNHDService.deleteBalanceToPointRecordCNHDByIds(ids));
//    }
    /**
     * 余额提现为CNHD
     * @return
     */
    @PostMapping("/withdrawal/balance")
    public R createWithdrawalBalance(@RequestBody UserWithdrawalDTO userWithdrawalDTO) {

        if (balanceToPointRecordCNHDService.createWithdrawalBalance(userWithdrawalDTO)){
            return R.ok();
        }else {
            return R.error();
        }
//        return R.error("该功能已关闭");
    }
}
